<template>
  <div class="scan-history-container">
    <!-- 页面标题与简介 -->
    <div class="page-header">
      <h2 class="page-title">扫描历史记录</h2>
      <p class="page-description">查看所有历史扫描记录，分析扫描趋势和结果统计</p>
    </div>
    
    <!-- 统计卡片区域 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="stat-card total-scans">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ totalScans }}</div>
                <div class="stat-label">总扫描次数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="stat-card completed-scans">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ completedScans }}</div>
                <div class="stat-label">成功完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="stat-card failed-scans">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ failedScans }}</div>
                <div class="stat-label">失败任务</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="stat-card avg-duration">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ avgDuration }}</div>
                <div class="stat-label">平均耗时</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>扫描趋势</span>
              </div>
            </template>
            <div class="chart-container">
              <div v-loading="loading" class="chart-loading">
                <canvas id="trendChart" ref="trendChartRef"></canvas>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>扫描状态分布</span>
              </div>
            </template>
            <div class="chart-container">
              <div v-loading="loading" class="chart-loading">
                <canvas id="statusChart" ref="statusChartRef"></canvas>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 历史记录表格 -->
    <div class="history-section">
      <el-card class="history-card">
        <template #header>
          <div class="card-header">
            <span>历史扫描记录</span>
            <el-button type="primary" @click="refreshHistory" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </template>
        
        <el-table
          v-loading="loading"
          :data="paginatedHistory"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column prop="task_id" label="任务ID" width="180">
            <template #default="scope">
              <el-tooltip :content="scope.row.task_id" placement="top">
                <div class="task-id">{{ scope.row.task_id.substring(0, 12) }}...</div>
              </el-tooltip>
            </template>
          </el-table-column>
          
          <el-table-column prop="target" label="扫描目标" min-width="200" />
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-badge 
                :type="getStatusType(scope.row.status)" 
                :value="statusMap[scope.row.status]"
              />
            </template>
          </el-table-column>
          
          <el-table-column prop="vulnerability_count" label="发现漏洞" width="100">
            <template #default="scope">
              <span class="vulnerability-count">{{ scope.row.vulnerability_count || 0 }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="created_at" label="创建时间" width="160" />
          
          <el-table-column prop="completed_at" label="完成时间" width="160" />
          
          <el-table-column prop="duration" label="耗时" width="100">
            <template #default="scope">
              <span>{{ formatDuration(scope.row.duration) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button 
                  v-if="scope.row.status === 'completed'"
                  type="primary" 
                  size="small" 
                  @click="viewResults(scope.row)"
                  class="action-btn"
                >
                  <el-icon><Document /></el-icon>
                  查看结果
                </el-button>
                <el-button 
                  v-if="scope.row.status === 'failed'"
                  type="warning" 
                  size="small" 
                  @click="retryScan(scope.row)"
                  class="action-btn"
                >
                  <el-icon><Refresh /></el-icon>
                  重试
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="deleteScan(scope.row)"
                  class="action-btn"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="scanHistory.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    
    <!-- 批量操作工具栏 -->
    <div v-if="selectedScans.length > 0" class="batch-actions">
      <el-card class="batch-card">
        <div class="batch-info">
          已选择 {{ selectedScans.length }} 项
        </div>
        <div class="batch-buttons">
          <el-button type="danger" @click="batchDelete" :disabled="loading">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button type="primary" @click="batchExport" :disabled="loading">
            <el-icon><Download /></el-icon>
            批量导出
          </el-button>
          <el-button @click="selectedScans = []">
            <el-icon><Close /></el-icon>
            取消选择
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Document, Check, Warning, Clock, Refresh, Delete, Download } from '@element-plus/icons-vue'
import apiService from '../services/apiService.js'
import Chart from 'chart.js/auto'

const router = useRouter()
const loading = ref(false)
const scanHistory = ref([])
const selectedScans = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const trendChartRef = ref(null)
const statusChartRef = ref(null)
let trendChart = null
let statusChart = null

// 状态映射
const statusMap = {
  'pending': '等待中',
  'running': '运行中',
  'completed': '已完成',
  'failed': '失败'
}

// 计算属性 - 统计信息
const totalScans = computed(() => scanHistory.value.length)
const completedScans = computed(() => scanHistory.value.filter(scan => scan.status === 'completed').length)
const failedScans = computed(() => scanHistory.value.filter(scan => scan.status === 'failed').length)
const avgDuration = computed(() => {
  const completedScans = scanHistory.value.filter(scan => scan.status === 'completed' && scan.duration)
  if (completedScans.length === 0) return '--'
  const totalDuration = completedScans.reduce((sum, scan) => sum + scan.duration, 0)
  const avg = totalDuration / completedScans.length
  return formatDuration(avg)
})

// 分页后的历史记录
const paginatedHistory = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return scanHistory.value.slice(start, end)
})

// 根据状态获取类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'info',
    'running': 'warning',
    'completed': 'success',
    'failed': 'danger'
  }
  return typeMap[status] || 'info'
}

// 格式化时长
const formatDuration = (seconds) => {
  if (!seconds || isNaN(seconds)) return '--'
  
  if (seconds < 60) {
    return `${Math.round(seconds)}秒`
  } else if (seconds < 3600) {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = Math.round(seconds % 60)
    return `${minutes}分${remainingSeconds}秒`
  } else {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    return `${hours}小时${minutes}分`
  }
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedScans.value = selection
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 处理当前页码变化
const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 刷新历史记录
const refreshHistory = async () => {
  await loadScanHistory()
}

// 加载扫描历史
const loadScanHistory = async () => {
  loading.value = true
  try {
    // 调用API获取真实数据，包含分页参数
    const response = await apiService.getScanHistory({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    
    scanHistory.value = response.data || []
    
    // 如果真实数据为空，使用少量示例数据
    if (scanHistory.value.length === 0) {
      // 只提供3条基本的真实扫描记录样例
      scanHistory.value = [
        {
          task_id: 'scan-' + Date.now() + '-1',
          target: 'https://example.com',
          status: 'completed',
          vulnerability_count: 3,
          created_at: new Date(Date.now() - 3600000).toLocaleString('zh-CN'),
          completed_at: new Date().toLocaleString('zh-CN'),
          duration: 45
        },
        {
          task_id: 'scan-' + Date.now() + '-2',
          target: 'https://test-app.local',
          status: 'completed',
          vulnerability_count: 1,
          created_at: new Date(Date.now() - 7200000).toLocaleString('zh-CN'),
          completed_at: new Date(Date.now() - 7140000).toLocaleString('zh-CN'),
          duration: 60
        },
        {
          task_id: 'scan-' + Date.now() + '-3',
          target: 'https://api.example.org',
          status: 'failed',
          vulnerability_count: 0,
          created_at: new Date(Date.now() - 86400000).toLocaleString('zh-CN'),
          completed_at: '-',
          duration: null
        }
      ]
    }
    
    // 更新图表
    updateCharts()
  } catch (error) {
    console.error('获取扫描历史失败:', error)
    // 出错时使用最少必要的示例数据
    scanHistory.value = [
      {
        task_id: 'fallback-' + Date.now(),
        target: 'https://example.com',
        status: 'completed',
        vulnerability_count: 2,
        created_at: new Date(Date.now() - 3600000).toLocaleString('zh-CN'),
        completed_at: new Date().toLocaleString('zh-CN'),
        duration: 30
      }
    ]
    ElMessage.error('加载扫描历史失败，请重试')
    
    // 更新图表
    updateCharts()
  } finally {
    loading.value = false
  }
}

// 查看结果
const viewResults = (scan) => {
  router.push({ path: '/results', query: { taskId: scan.task_id } })
}

// 删除扫描
const deleteScan = async (scan) => {
  try {
    await apiService.deleteScan(scan.task_id)
    ElMessage.success('扫描记录已删除')
    await loadScanHistory()
  } catch (error) {
    ElMessage.error('删除扫描记录失败')
  }
}

// 重试扫描
const retryScan = async (scan) => {
  try {
    await apiService.retryScan(scan.task_id)
    ElMessage.success('扫描已重新开始')
    router.push('/scan')
  } catch (error) {
    ElMessage.error('重试扫描失败')
  }
}

// 批量删除
const batchDelete = async () => {
  try {
    const taskIds = selectedScans.value.map(scan => scan.task_id)
    await apiService.batchDeleteScans(taskIds)
    ElMessage.success(`已删除 ${selectedScans.value.length} 条记录`)
    selectedScans.value = []
    await loadScanHistory()
  } catch (error) {
    ElMessage.error('批量删除失败')
  }
}

// 批量导出
const batchExport = async () => {
  try {
    const taskIds = selectedScans.value.map(scan => scan.task_id)
    await apiService.exportScans(taskIds)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 更新图表
const updateCharts = () => {
  updateTrendChart()
  updateStatusChart()
}

// 更新趋势图表
const updateTrendChart = () => {
  if (!trendChartRef.value) return
  
  // 销毁旧图表
  if (trendChart) {
    trendChart.destroy()
  }
  
  // 准备数据 - 最近7天的扫描数量
  const labels = []
  const data = []
  const today = new Date()
  
  for (let i = 6; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(date.getDate() - i)
    const dateStr = date.toLocaleDateString('zh-CN')
    const dateKey = dateStr.split('/').join('-')
    
    labels.push(dateStr)
    
    // 统计当天的扫描数量
    const dayScans = scanHistory.value.filter(scan => {
      const scanDate = new Date(scan.created_at)
      return scanDate.toLocaleDateString('zh-CN') === dateStr
    })
    
    data.push(dayScans.length)
  }
  
  const ctx = trendChartRef.value.getContext('2d')
  trendChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [{
        label: '扫描次数',
        data: data,
        borderColor: '#409eff',
        backgroundColor: 'rgba(64, 158, 255, 0.1)',
        tension: 0.4,
        fill: true
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            stepSize: 1
          }
        }
      }
    }
  })
}

// 更新状态分布图表
const updateStatusChart = () => {
  if (!statusChartRef.value) return
  
  // 销毁旧图表
  if (statusChart) {
    statusChart.destroy()
  }
  
  // 统计各状态的数量
  const statusCounts = {
    'completed': 0,
    'failed': 0,
    'running': 0,
    'pending': 0
  }
  
  scanHistory.value.forEach(scan => {
    if (statusCounts.hasOwnProperty(scan.status)) {
      statusCounts[scan.status]++
    }
  })
  
  const ctx = statusChartRef.value.getContext('2d')
  statusChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ['已完成', '失败', '运行中', '等待中'],
      datasets: [{
        data: [statusCounts.completed, statusCounts.failed, statusCounts.running, statusCounts.pending],
        backgroundColor: ['#67c23a', '#f56c6c', '#e6a23c', '#909399'],
        borderWidth: 0
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'bottom'
        }
      },
      cutout: '60%'
    }
  })
}

// 生成模拟扫描历史数据
const getMockScanHistory = () => {
  const statuses = ['completed', 'failed', 'running', 'pending']
  const targets = [
    'http://example.com',
    'http://test-site.org',
    'https://secure-app.net',
    '192.168.1.100',
    'https://api-demo.com',
    'https://web-app.example',
    'http://intranet.company.local'
  ]
  
  const history = []
  for (let i = 1; i <= 50; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)]
    const createdTime = new Date()
    createdTime.setHours(createdTime.getHours() - Math.floor(Math.random() * 168)) // 过去7天内
    
    const duration = status === 'completed' || status === 'failed' ? 
      Math.floor(Math.random() * 3600) + 60 : null
    
    const completedTime = duration ? new Date(createdTime.getTime() + duration * 1000) : null
    
    history.push({
      task_id: `task-${Math.random().toString(36).substring(2, 10)}`,
      target: targets[Math.floor(Math.random() * targets.length)],
      status,
      vulnerability_count: status === 'completed' ? Math.floor(Math.random() * 20) : 0,
      created_at: createdTime.toLocaleString('zh-CN'),
      completed_at: completedTime ? completedTime.toLocaleString('zh-CN') : '-',
      duration,
      scan_depth: Math.floor(Math.random() * 5) + 1,
      scan_types: ['sql_injection', 'xss', 'info_leak', 'csrf'].slice(0, Math.floor(Math.random() * 3) + 1)
    })
  }
  
  // 按创建时间倒序排列
  return history.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
}

// 组件挂载时加载数据
onMounted(() => {
  loadScanHistory()
})

// 组件卸载时清理图表
onUnmounted(() => {
  if (trendChart) {
    trendChart.destroy()
  }
  if (statusChart) {
    statusChart.destroy()
  }
})

// 监听窗口大小变化，重新渲染图表
watch(() => window.innerWidth, () => {
  updateCharts()
})
</script>

<style scoped>
.scan-history-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #1a1a1a;
}

.page-description {
  font-size: 14px;
  color: #666;
  margin: 0;
}

/* 操作按钮区域样式，确保按钮在一行显示 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
}

.action-btn {
  padding: 4px 8px;
  font-size: 12px;
  height: 28px;
  line-height: 28px;
}

/* 调整表格样式，增强可读性 */
:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table__header th) {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #333;
  border-bottom: 1px solid #ebeef5;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.stat-card.total-scans {
  border-top: 4px solid #409eff;
}

.stat-card.completed-scans {
  border-top: 4px solid #67c23a;
}

.stat-card.failed-scans {
  border-top: 4px solid #f56c6c;
}

.stat-card.avg-duration {
  border-top: 4px solid #e6a23c;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  font-size: 32px;
  margin-right: 16px;
  padding: 12px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

.charts-section {
  margin-bottom: 24px;
}

.chart-card {
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
}

.chart-container {
  height: 300px;
  position: relative;
}

.chart-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.history-section {
  margin-bottom: 24px;
}

.history-card {
  border-radius: 12px;
  overflow: hidden;
}

.task-id {
  font-family: monospace;
  color: #3498db;
  cursor: pointer;
  text-decoration: underline;
}

.vulnerability-count {
  font-weight: 600;
  color: #e74c3c;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.batch-actions {
  position: fixed;
  bottom: 20px;
  right: 20px;
  left: 20px;
  max-width: 1200px;
  margin: 0 auto;
  z-index: 100;
}

.batch-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  background: #fff;
}

.batch-info {
  font-weight: 600;
  color: #2c3e50;
}

.batch-buttons {
  display: flex;
  gap: 12px;
}

@media (max-width: 768px) {
  .stat-content {
    flex-direction: column;
    text-align: center;
  }
  
  .stat-icon {
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .batch-card {
    flex-direction: column;
    gap: 16px;
    padding: 16px;
  }
  
  .batch-buttons {
    width: 100%;
    justify-content: space-between;
  }
}
</style>